package com.intro.manager.impl;

import java.io.File;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.intro.database.dao.NewsDao;
import com.intro.database.dao.QueryDao;
import com.intro.database.entity.News;
import com.intro.manager.INewsManager;
import com.intro.util.Constants;
import com.intro.util.Page;

public class NewsManagerImpl implements INewsManager {
	

	private NewsDao newDao = new NewsDao();
	
	private QueryDao queryDao = new QueryDao();
	
	//注 所有的currentPage都从第一页开始算
	
	public int addNews(News news) {
		int result = OPER_SUCC;
		if(news==null) {
			System.out.println("传入新闻为空");
			result =  OPER_FAIL;
		} else {
			if(!newDao.save(news)) {
				result = OPER_FAIL;
			}
		}
		return result;
	}

	public List<News> findAllNews() {
		//queryDao.findByPropertyInPageWithSort(News.class, "type", 1, "date", Constants.DESC, 1, Integer.MAX_VALUE).getPageList();
		News news = new News();
		news.setType(News.TYPE_NEWS);
		return queryDao.findByExample(News.class,news );
	}

	public Page findAllNews(int currentPage, int pageSize) {
		
		return queryDao.findByPropertyInPageWithSort(News.class, "type", News.TYPE_NEWS, "date", Constants.DESC, currentPage, pageSize);
	}

	public News findByNewsId(int newsId) {
		return queryDao.findById(News.class, newsId);
	}

	public int deleteNews(int newsId) {
		News news = findByNewsId(newsId);
		
		int result = OPER_SUCC;
		if(news!=null) {
			if(newDao.delete(news)) {
				String imagesSrc = news.getImagePath();
				String rootPath = ServletActionContext.getServletContext().getRealPath("");
				System.out.println(rootPath);
				File f = new File(rootPath+"\\"+imagesSrc);
				if(f.exists())
					f.delete();
			}
		} else {
			result = OPER_FAIL;
			System.out.println("新闻为空");
		}
		return result;
	}

	public int updateNews(News news) {
		News n = newDao.updateNews(news);
		int result = OPER_FAIL;
		if(n!=null) {
			result = OPER_SUCC;
		}
		return result;
	}
	
	

	public Page findAllProject(int currentPage, int pageSize) {
		return queryDao.findByPropertyInPageWithSort(News.class, "type", News.TYPE_PROJECT, "date", Constants.DESC, currentPage, pageSize);
	}
	

}
